package com.weige.conver.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;

@Component
public class JsonUtils {

    public static HashMap<String,String> GetAreaCode(String fileName){
        HashMap<String,String> map = new HashMap<>();
        InputStreamReader inputStreamReader = null;
        FileInputStream fileInputStream = null;
        try {
            File file = new File(FileUtils.jsonFilePath(fileName));
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
            String str = IOUtils.toString(inputStreamReader);
            map = JSONObject.parseObject(str, HashMap.class);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());;
        }finally {
            try {
                fileInputStream.close();
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    //读取json文件
    public static JSONObject readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(FileUtils.jsonFilePath(fileName));
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void writerJsonFile(String filName,JSONObject data) throws IOException {
        File file = new File(FileUtils.jsonFilePath(filName));
        FileOutputStream fos = new FileOutputStream(file, false);
        String d = JSONObject.toJSONString(data);
        fos.write(d.getBytes());
        fos.close();
    }


    public String addSigId(String deviceId,String sigFile) throws IOException {
        String sigId = DateUtils.getCurrentTime();
        JSONObject sigData = JsonUtils.readJsonFile(sigFile);
        sigData.put(deviceId,sigId);
        JsonUtils.writerJsonFile(sigFile,sigData);
        return sigId;
    }

}
